import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';

import '../common/api_service.dart';
import '../common/constants.dart';
import '../common/routes.dart';
import '../model/tab_data_model.dart';
import '../widgets/error_view.dart';
import 'pipe_data_list_page.dart';

class PipeListPage extends StatefulWidget {
  const PipeListPage({super.key});

  @override
  State<PipeListPage> createState() => _PipeListPageState();
}

class _PipeListPageState extends State<PipeListPage> with SingleTickerProviderStateMixin {
  TabController? _tabController;
  final List<TabDataModel> _tabDataList = [];
  bool _isShowError = false;

  @override
  void initState() {
    super.initState();
    _fetchTabList();
  }

  void _fetchTabList() {
    ApiService().getHomeTagList((list) {
      _tabDataList.clear();
      _tabDataList.addAll(list);
      setState(() {
        _tabController = TabController(length: _tabDataList.length, vsync: this);
      });
    }, () {
      setState(() {
        _isShowError = true;
      });
    });
  }

  void _getActivityInfo() {
    ApiService().getActivityInfo((data) {
      var map = data as Map<String, dynamic>;
      if (map["contentType"] == "pipe") {
        var pipeId = map["value"];
        Get.toNamed(Routes.CHAT, arguments: {"pipeId": pipeId});
      }
    }, () {});
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            Expanded(
              child: InkWell(
                onTap: () {
                  Get.toNamed(Routes.SEARCH);
                },
                child: Container(
                  decoration: BoxDecoration(color: Colors.grey[200], borderRadius: BorderRadius.circular(8)),
                  child: const Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
                      child: Text('搜索内容/角色', style: TextStyle(fontSize: 16, color: Colors.black38)),
                    ),
                  ),
                ),
              ),
            ),
            Container(width: 10),
            SizedBox(
              child: TextButton(
                style: TextButton.styleFrom(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                  backgroundColor: Constants.themeColor,
                  foregroundColor: Colors.white,
                ),
                onPressed: () {
                  _getActivityInfo();
                },
                child: const Text("我的私密角色", style: TextStyle(fontSize: 16)),
              ),
            )
          ],
        ),
        bottom: _tabController != null
            ? TabBar(
                controller: _tabController,
                tabAlignment: TabAlignment.start,
                isScrollable: true,
                indicatorColor: Constants.themeColor,
                indicatorSize: TabBarIndicatorSize.label,
                indicatorPadding: const EdgeInsets.symmetric(vertical: 3),
                labelPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                labelStyle: TextStyle(color: Constants.themeColor, fontWeight: FontWeight.w600),
                unselectedLabelStyle: const TextStyle(color: Colors.black54),
                dividerColor: Colors.grey[200],
                splashFactory: NoSplash.splashFactory,
                tabs: _tabDataList.map((data) => Tab(text: data.tag)).toList(),
              )
            : null,
      ),
      body: Stack(
        children: [
          _tabDataList.isNotEmpty
              ? TabBarView(
                  controller: _tabController,
                  children: _tabDataList.map((data) {
                    return PipeDataListPage(tabModel: data);
                  }).toList(),
                )
              : Center(
                  child: Lottie.asset('assets/lotties/loading.json'),
                ),
          Offstage(
            offstage: !_isShowError,
            child: ErrorView(retryAction: () {
              _fetchTabList();
            }),
          ),
        ],
      ),
    );
  }
}
